<?php 

class Silk_Pms_Adminhtml_ExchangeController extends Mage_Adminhtml_Controller_Action
{
	protected function _initAction()
	{
		$this->loadLayout()->_setActiveMenu("pms/exchange")->_addBreadcrumb(Mage::helper("adminhtml")->__("积分兑换管理"),Mage::helper("adminhtml")->__("兑换管理列表"));
		
		return $this;
	}

	public function indexAction()
	{
		$this->loadLayout();
	    $this->renderLayout();
	}

	public function newAction()
	{
		$id = $this->getRequest()->getParam('id');
		if($id){
			$model=Mage::getModel("pms/exchange")->load($id);
			Mage::register("exchange",$model);
		}
		$this->loadLayout();
	    $this->renderLayout();
	}

	public function saveAction(){
		$Id = $this->getRequest()->getParam("id");
		$name = $this->getRequest()->getParam('name');
		$start = $this->getRequest()->getParam('start_at');
		$end = $this->getRequest()->getParam('end_at');
		$status = $this->getRequest()->getParam('status');
		$websiteId = $this->getRequest()->getParam('website');
		$description = $this->getRequest()->getParam('description');
		$session = Mage::getSingleton('admin/session');
		if(!$websiteId){
			$websiteId =$session->getUser()->getWebsiteId();
		}
		$adminId = $session->getUser()->getId();
		$data = array(
			"name"=>$name,
			"start_at"=>$start,
			"end_at"=>$end,
			"status"=>$status,
			"description"=>$description,
			"website_id"=>$websiteId,
			"admin_id" =>$adminId
		);
		$model = Mage::getModel("pms/exchange")
				->addData($data)
				->setId($this->getRequest()->getParam("id"));
		$model->save();

		$model = Mage::getModel("pms/exchange")->load($model->getId());
		$templetId = $model->getTemplateId();
		$products = $this->getRequest()->getParam('product');

		if($model && $model->getId() && count($products)){
			$activeId = $model->getId();
			foreach ($products as $key => $value) {
				$datas = array(
					"product_id"=>$value[0],
					"qty" =>$value[1],
					"name"=>$value[2],
					"sku"=>$value[3],
					"activity_id"=>$activeId,
					"position"=>$value[4],
					"points"=>$value[6],
					);
				$exId = $value[5]?$value[5]:null;
				$exchangeproduct = Mage::getModel("pms/exchangeproduct")
				->addData($datas)->setId($exId);
				$exchangeproduct->save();
				$website = Mage::getModel('core/website')->load($websiteId);
				$storeId = $website->getDefaultStore()->getId();
				$productmodel = Mage::getModel("catalog/product")->setStoreId($storeId)->load($value[0]);
				$usePoint = $productmodel->getUsePoint(); 
				if(!$usePoint){
					$productmodel->setUsePoint(1);
					$productmodel->save();
				}
			}
			$formData = $model->getFormData();
			if($formData && $templetId){
				$formData = json_decode($formData,true);
		    	$exchangeproducts = Mage::getModel("pms/exchangeproduct")
		    					                  ->getCollection()
		    					                  ->addFieldToFilter("activity_id",$activeId)
		    					                  ->setOrder('position', "ASC");
		    	if($exchangeproducts->count()){
		    		$product=array();
		    		foreach ($exchangeproducts as $value) {
						$product[] = $value->getProductId();
		    		}
		    	}
				if(count($product)){
					if($templetId==1){
						if(count($product)>2){
							$formData["hot"] = array_slice($product,0,2);
							$formData["sell"] =array_slice($product,2);	 
						}else{
							$formData["hot"] = $product;
							$formData["sell"] = array();
						}	       
					}else{
						if(count($product)>4){
							$formData["hot"] = array_slice($product,0,4);
							$formData["sell"] =array_slice($product,4);
						}else{
							$formData["hot"] = $product;
							$formData["sell"] = array();
						}
					}
				}else{
					$formData["hot"] = array();
					$formData["sell"] = array();			
				}
				$formData = json_encode($formData);
				$model->setFormData($formData)->save();
			}	
		}
		
		$templetId = $templetId?$templetId:null;
		$result = array('success'=>true,'message'=>"活动保存成功","exchange_id"=> $model->getId(),"template_id"=>$templetId);
		echo json_encode($result);
	}


	//商品列表
	public function productlistAction(){
		$result = array('error'=>true,'message'=>'');
		$sku = $this->getRequest()->getParam('sku');
		$name = $this->getRequest()->getParam('name');
		$productId = $this->getRequest()->getParam('product_id');
		$websiteId = $this->getRequest()->getParam('websiteId');
		$website = Mage::getModel('core/website')->load($websiteId);
		$storeId = $website->getDefaultStore()->getId();
		$collection = Mage::getModel("catalog/product")->getCollection()->addAttributeToSelect('*');
		if (Mage::helper('catalog')->isModuleEnabled('Mage_CatalogInventory')) {
		    $collection->joinField('qty',
		        'cataloginventory/stock_item',
		        'qty',
		        'product_id=entity_id',
		        '{{table}}.stock_id=1 AND {{table}}.website_id = ' . $websiteId,
		        'left');
		}
		$collection->joinAttribute(
            'status',
            'catalog_product/status',
            'entity_id',
            null,
            'inner',
            $storeId
        );
	    $collection->joinAttribute(
		    'storename',
		    'catalog_product/name',
		    'entity_id',
		    null,
		    'inner',
		    $storeId
		);
		$collection->addAttributeToFilter('status', array('eq' => Mage_Catalog_Model_Product_Status::STATUS_ENABLED));

		if($sku)
		{
			$collection->addAttributeToFilter('sku',array('eq'=>$sku));
		}
		if($name)
		{
			$name = str_replace("replace","/",$name);
			$collection->addAttributeToFilter('storename',array('eq'=>$name));
		}
		if($productId){
			$collection->addAttributeToFilter('entity_id',array('eq'=>$productId));
		}

		$isShowOutOfStock = Mage::getStoreConfigFlag('cataloginventory/options/show_out_of_stock');
        if(!$isShowOutOfStock)
        {
            Mage::getSingleton('cataloginventory/stock')->addInStockFilterToCollection($collection);
        }

		if($collection->count())
        {
            $product = $collection->getFirstItem();
        }else{
        	$result['message'] ="此商品在此站点不可用或不存在";
        	echo  json_encode($result);
        	return;
        }

		$data = array(
			"product_id"=>$product->getId(),
			"sku"=>$product->getSku(),
			"name"=>$product->getStorename(),
			"websiteqty"=>$product->getQty()
			);

        $html = <<<HTML
				<tr class="parent">
					<td class="productid">{$data['product_id']}</td>
					<td class="productname">{$data['name']}</td>
					<td class="productsku">{$data['sku']}</td>
					<td><input onblur="checkInt(this)" class="qtys" type="text" product="{$data['product_id']}" pname="{$data['name']}" sku="{$data['sku']}" name="qty"  websiteqty = "{$data['websiteqty']}"/></td>
					<!--<td><input onblur="checkInt(this)" class ="points" type="text" name = "points" /></td>-->
					<td><input onblur="checkInt(this)" class ="position" type="text" name = "position" /></td>
					
					<td>0</td>				
					<td><p class="remove">删除</p></td>
				 </tr>
HTML;
		$result = array('error'=>false,'message'=>$html);
		echo json_encode($result);

	}

	public function removeproductAction(){
		$result = array('error'=>false,'message'=>'');
		$exchangeproductId = $this->getRequest()->getParam('exchangeproductId');
		$activity_id = $this->getRequest()->getParam('activity_id');
		try{
			$exchangeproduct = Mage::getModel("pms/exchangeproduct")->load($exchangeproductId);
			$productId = $exchangeproduct->getProductId();
			$model = Mage::getModel("pms/exchange")->load($activity_id);
			//删除formdata中产品
			$formData = $model->getFormData();
			$formData = json_decode($formData,true);

			foreach ($formData["hot"] as $key => $value) {
				if($value == $productId){
					unset($formData["hot"][$key]);
				}
			}
			foreach ($formData["sell"] as $key => $value) {
				if($value == $productId){
					unset($formData["sell"][$key]);
				}
			}

			$formData = json_encode($formData);
			$model->setFormData($formData)->save();

			$websiteId = $model->getWebsiteId();
			$website = Mage::getModel('core/website')->load($websiteId);
			$storeId = $website->getDefaultStore()->getId();

			$productmodel = Mage::getModel("catalog/product")->setStoreId($storeId)->load($productId);
			$usePoint = $productmodel->getUsePoint(); 
			if($usePoint){
				$productmodel->setUsePoint(0);
				$productmodel->save();
			}
		 	$exchangeproduct->delete();
		}catch(Exception $e){
			$result = array('error'=>true,'message'=>$e->getMessage());
		}
		echo json_encode($result);

	}
	public function massRemoveAction(){
		try {
			$ids = $this->getRequest()->getPost('ids', array());
			foreach ($ids as $id) {
				$model = Mage::getModel("pms/exchange");
				$model->setId($id)->delete();
				$exchangeproducts = Mage::getModel("pms/exchangeproduct")
				                  ->getCollection()
				                  ->addFieldToFilter("activity_id",$id);
				if($exchangeproducts->count()){
						foreach ($exchangeproducts as $item) {
							Mage::getModel("pms/exchangeproduct")->load($item->getId())->delete();
						}
				}
				  
			}
			Mage::getSingleton("adminhtml/session")->addSuccess(Mage::helper("adminhtml")->__("已删除！"));
		}
		catch (Exception $e) {
			Mage::getSingleton("adminhtml/session")->addError($e->getMessage());
		}
		$this->_redirect('*/*/');
	}

	public function massChangeStatusAction(){
		try{
			$ids = $this->getRequest()->getPost('ids', array());
			$status = $this->getRequest()->getPost('status');
			foreach ($ids as $id) {
				$model = Mage::getModel("pms/exchange")->load($id);
				$model->setStatus($status);
				$model->save();
			}
			Mage::getSingleton("adminhtml/session")->addSuccess(Mage::helper("adminhtml")->__("状态已修改"));
		}
		catch (Exception $e) {
			Mage::getSingleton("adminhtml/session")->addError($e->getMessage());
		}
		$this->_redirect('*/*/');
	}
	protected function _isAllowed()
    {
        return Mage::getSingleton('admin/session')->isAllowed('pms/exchange');
    }

    public function editAction(){
    	$id = $this->getRequest()->getParam('exchangeId');
    	$this->loadLayout();
        $this->renderLayout();
    }

    public function loadTempletAction(){
    	$result = array('error'=>true,'message'=>'');
    	$value = $this->getRequest()->getParam("value");
    	$exchangeId = $this->getRequest()->getParam("exchange_id");
    	$arr = array(1,2,3);
    	if(!in_array($value, $arr)){
    		$result["message"]= "这个模板不存在";
    		return false;
    	}
    	$block = $this->getLayout()->createBlock('pms/adminhtml_exchange_templte');
    	$url = "pms/exchange/edit/templte".$value.".phtml";
        $block->setTemplate($url);
        $message =  $block->toHtml();
        $result = array('error'=>false,'message'=>$message);
        $data = json_encode($result);
        $response = $this->getResponse();
		$response->setHeader('Content-type', 'application/json');
		$response->setBody($data);
    }

    public function saveTempletAction(){
    	$data =$this->getRequest()->getPost("form_data");
    	$templet = $this->getRequest()->getParam("templet");
    	$exchangeId = $this->getRequest()->getParam("exchangeId");
    	$exchangeproducts = Mage::getModel("pms/exchangeproduct")
    					                  ->getCollection()
    					                  ->addFieldToFilter("activity_id",$exchangeId)
    					                  ->setOrder('position', "ASC");
    	if($exchangeproducts->count()){
    		foreach ($exchangeproducts as $value) {
				$product[] = $value->getProductId();
    		}
    		if($templet==1){
    			if(count($product)>2){
    				$data["hot"] = array_slice($product,0,2);
    				$data["sell"] =array_slice($product,2);	 
    			}else{
    				$data["hot"] = $product;
    				$data["sell"] = array();
    			}
    			       
    		}else{
    			if(count($product)>4){
    				$data["hot"] = array_slice($product,0,4);
    				$data["sell"] =array_slice($product,4);
    			}else{
    				$data["hot"] = $product;
    				$data["sell"] = array();
    			}

    		}
    	}else{
    		$data["hot"] = array();
    		$data["sell"] = array();
    	}
       	$image =$_FILES["image"];
    	$imagearr =$this->getImage($image); 
    	$upload = Mage::helper("pms/fileupload");
    	try{
    		$images = $upload->upload($imagearr,"exchange");		
    	}catch(Exception $e){
			Mage::getSingleton("adminhtml/session")->addError($e->getMessage());
    	}

    	$model = Mage::getModel("pms/exchange")->load($this->getRequest()->getParam("exchangeId"));
    	if($model && $model->getId() && $model->getFormData()){
    		$olddata = $model->getFormData();
    		$oldresult = json_decode($olddata,true);
    		$oldimage = $oldresult["image"];
    		foreach ($images as $key => $value) {
    			if($value){
    				$images[$key]=$value;
    			}else{
    				$images[$key] = $oldimage[$key];
    			}
    		}
    		
    	}			                   
      
    	$data["image"]=$images;
    	$datas = json_encode($data);
		try{
			$model = Mage::getModel("pms/exchange")
					->setFormData($datas)
					->setTemplateId($this->getRequest()->getParam("templet"))
					->setId($this->getRequest()->getParam("exchangeId"));
			$model->save();
		}
		catch (Exception $e) {
			Mage::getSingleton("adminhtml/session")->addError($e->getMessage());
		}
		$this->_redirect('*/*/');

    }

    public function resettemplateAction(){
    	$exchangeId = $this->getRequest()->getParam("exchange_id");
    	$template_id = $this->getRequest()->getParam("template_id");
    	if(!$template_id){
    		$result = array('error'=>true,'message'=>'');
    		echo json_encode($result);
    		return;
    	}
    	$model = Mage::getModel("pms/exchange")->load($exchangeId);
    	$result = $model->getFormData();
    	$data = json_decode($result,true);
    	$images = array("banner"=>"","hot"=>"","sell"=>"","active"=>"");
    	$data["image"] = $images;
    	$data["hotbackendcolor"]="#da292e";
    	$data["sellbackendcolor"]="#00dcc6";
    	if(isset($data["activebackendcolor"])){
    		$data["activebackendcolor"]="#fff";
    	}
    	$datas = json_encode($data);
    	try{
    		$model->setFormData($datas)->save();
    	}catch(Exception $e){
    		$result = array('error'=>false,'message'=>$e->getMessage());
    	}
    	$result = array('error'=>true,'message'=>'');
    	echo json_encode($result);

    }

    //多图片上传转换
    public function getImage($image){
	   	foreach ($image as $key => $value) {
				foreach ($value as $k => $v) {
					$imagearr[$k][$key]=$v[0];
				}
	   	}
	   	return $imagearr;

    }
  
}